package com.atguigu.controller;

import com.atguigu.common.result.R;
import com.atguigu.service.PaymentService;
import com.atguigu.service.WeiXinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeiXinService weixinPayService;
    @Autowired
    private PaymentService  paymentService;

    /**
     * 下单，生成支付二维码
     */
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map map = weixinPayService.orderPayStatus(orderId);
        return R.ok().data(map);
    }
    @GetMapping("/queryPayStatus/{orderId}")
    public  R queryPayStatus(@PathVariable("orderId") Long orderId){
        //1、调用查询接口
        Map<String, String> resultMap = weixinPayService.queryPayStatus(orderId);
        if (resultMap == null) {
            return R.error().message("支付出错");
        }

        //2、支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,resultMap);
            return R.ok().message("支付成功");
        }

        return R.ok().message("支付中");


    }

}
